<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
            <el-form-item label="活动名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入活动名称" clearable style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="渠道名称" prop="channelId">
                <el-select v-model="queryParams.channelId" placeholder="请选择渠道" clearable style="width: 200px">
                    <el-option v-for="dict in channelOptions" :key="dict.channelId" :label="dict.channelName"
                        :value="dict.channelId" />
                </el-select>
            </el-form-item>
            <el-form-item label="活动状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable style="width: 200px">
                    <el-option v-for="dict in activityStatusOptions" :key="dict.dictCode" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="活动类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择活动类型" clearable style="width: 200px">
                    <el-option v-for="dict in activityTypeOptions" :key="dict.dictCode" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
            </el-col>
            <right-toolbar :show-search="showSearch" @update:show-search="showSearch = $event"
                @queryTable="getData"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="活动编号" prop="activityId" :show-overflow-tooltip="true" />
            <el-table-column label="活动名称" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="渠道名称" prop="channelName" :show-overflow-tooltip="true" />
            <el-table-column label="活动简介" prop="info" :show-overflow-tooltip="true" />
            <el-table-column label="活动类型" prop="type" align="center" :show-overflow-tooltip="true">
                <template #default="scope">
                    <el-tag :type="scope.row.type == 2 ? 'success' : 'info'">{{ scope.row.type == 2 ? '代金券' : '折扣券'
                    }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="活动明细" prop="voucher" width="180" align="center">
                <template #default="scope">
                    <span>{{ scope.row.type == 2 ? '代金券' : '折扣券' }}/{{ scope.row.discount }}{{ scope.row.type == 2 ? '元'
                        :
                        '折' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="活动状态" prop="activityStatus" :show-overflow-tooltip="true">
                <template #default="scope">
                    <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">{{ scope.row.status == 1 ? '正常' : '禁用'
                    }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="活动起始时间" prop="beginTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.beginTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="活动结束时间" prop="endTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.endTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10]"
            :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />

        <!-- 新增活动 -->
        <el-dialog :title="isEdit ? '编辑活动' : '添加活动'" v-model="addDialogVisible" width="600px"
            :close-on-click-modal="false">
            <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
                <el-form-item label="渠道来源" prop="channelId" required>
                    <el-select v-model="addForm.channelId" placeholder="渠道来源">
                        <el-option v-for="item in channelOptions" :key="item.channelId" :label="item.channelName"
                            :value="item.channelId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动名称" prop="name" required>
                    <el-input v-model="addForm.name" placeholder="请输入活动名称" />
                </el-form-item>
                <el-form-item label="活动日期" prop="activityTime" required>
                    <el-date-picker v-model="addForm.activityTime" type="datetimerange" start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 100%;" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="活动简介" prop="info" required>
                    <el-input v-model="addForm.info" placeholder="请输入活动简介" />
                </el-form-item>
                <el-form-item label="活动类型" prop="type" required>
                    <el-select v-model="addForm.type" placeholder="活动类型">
                        <el-option v-for="item in activityTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="折扣券" prop="discount" v-if="addForm.type === '1'" required>
                    <el-input-number v-model="addForm.discount" :min="0" :max="10" :step="0.01"
                        controls-position="right" style="width: 200px" :precision="2" />
                    <span style="margin-left: 8px;">折</span>
                </el-form-item>
                <el-form-item label="代金券" prop="voucher" v-if="addForm.type === '2'" required>
                    <el-input-number v-model="addForm.voucher" :min="0" :max="99999" :step="1" controls-position="right"
                        style="width: 200px" :precision="2" />
                    <span style="margin-left: 8px;">元</span>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted,getCurrentInstance } from "vue";
import { getlist, qudaomingcheng, huodongzhuangtai, huodongleixing, addhuodong, deletehuodong, edithuodong } from "../../../api/activity/Actiapi";
import { parseTime } from "@/utils/ruoyi";
import RightToolbar from "@/components/RightToolbar/index.vue";
import { ElMessage, ElMessageBox } from 'element-plus';
const {proxy} = getCurrentInstance();
const list = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const isEdit = ref(false);

const queryParams = reactive({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    name: undefined,
    channelId: undefined,
    status: undefined,
    type: undefined,
});

const queryRef = ref(null); // Ref for the form

// 渠道名称选项
const channelOptions = ref([]);
const getqudao = async () => {
    const res = await qudaomingcheng();
    if (res.code == 200) {
        channelOptions.value = res.data;
    }
}
getqudao();
//活动状态
const activityStatusOptions = ref([]);
const gethuodongzhuangtai = async () => {
    const res = await huodongzhuangtai();
    if (res.code == 200) {
        activityStatusOptions.value = res.data;
    }
}
gethuodongzhuangtai();
//活动类型
const activityTypeOptions = ref([]);
const gethuodongleixing = async () => {
    const res = await huodongleixing();
    if (res.code == 200) {
        activityTypeOptions.value = res.data;
    }
}
gethuodongleixing()

const getData = async () => {
    loading.value = true;
    queryParams.pageNum = pageNum.value;
    queryParams.pageSize = pageSize.value;
    const res = await getlist(queryParams);
    if (res.code == 200) {
        list.value = res.rows;
        total.value = res.total;
    }
    loading.value = false;
};

/** 搜索按钮操作 */
function handleQuery() {
    // console.log("查询条件：", queryParams)
    pageNum.value = 1;
    getData();
}

/** 重置按钮操作 */
function resetQuery() {
    queryRef.value.resetFields(); // Reset form fields
    handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.activityId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    isEdit.value = false;
    addDialogVisible.value = true;
    Object.assign(addForm, {
        channelId: '',
        name: '',
        activityTime: [],
        info: '',
        type: null,
        discount: 0,
        voucher: 0,
    });
}

/** 修改按钮操作 */
function handleUpdate(row) {
    isEdit.value = true;
    addDialogVisible.value = true;
    // console.log("修改数据：", row);
    // 回显数据
    Object.assign(addForm, {
        activityId: row.activityId,
        channelId: row.channelId,
        name: row.name,
        activityTime: [row.beginTime, row.endTime],
        info: row.info,
        type: row.type.toString(),
        discount: row.discount || 0,
        voucher: row.voucher || 0,
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const activityIds = row.activityId ? [row.activityId] : ids.value;
    ElMessageBox.confirm(
        '是否确认删除活动编号为"' + activityIds + '"的数据项？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await deletehuodong(activityIds);
            if (res.code === 200) {
                ElMessage.success({
                    type: "success",
                    message: res.msg
                });
                getData();
            }
        })
        .catch(() => {
            ElMessage.info("已取消删除");
        });
}

/** 导出按钮操作 */
function handleExport() {
    ElMessageBox.confirm('是否确认导出当前页面的商机数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 构建导出参数，确保字段名与后端接口一致
        const exportParams = {
            pageNum: pageNum.value,
            pageSize: pageSize.value,
        };
        // 使用download方法进行文件下载
        proxy.download("tienchin/course/export", exportParams, `course_${new Date().getTime()}.xlsx`);
    }).catch(() => { });
    // Implement export logic here, similar to business/index.vue if using backend export
}

/** 分页大小改变 */
const handleSizeChange = (val) => {
    pageSize.value = val;
    getData();
};

/** 当前页改变 */
const handleCurrentChange = (val) => {
    pageNum.value = val;
    getData();
};

const addDialogVisible = ref(false);
const addFormRef = ref(null);
const addForm = reactive({
    activityId: null,
    channelId: null,
    name: '',
    activityTime: [],
    info: '',
    type: '',
    discount: 0,
    voucher: 0,
});
const addRules = {
    channelId: [{ required: true, message: '请选择渠道来源', trigger: 'change' }],
    name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
    activityTime: [{ required: true, message: '请选择活动日期', trigger: 'change' }],
    info: [{ required: true, message: '请输入活动简介', trigger: 'blur' }],
    type: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
    discount: [
        {
            required: true,
            message: '请输入折扣券数值',
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (addForm.type === '1' && (!value || value <= 0 || value > 10)) {
                    callback(new Error('折扣券必须大于0且小于等于10'));
                } else {
                    callback();
                }
            }
        }
    ],
    voucher: [
        {
            required: true,
            message: '请输入代金券数值',
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (addForm.type === '2' && (!value || value <= 0)) {
                    callback(new Error('代金券必须大于0'));
                } else {
                    callback();
                }
            }
        }
    ]
};

// 新增表单提交
async function submitAddForm() {
    addFormRef.value.validate(async (valid) => {
        if (valid) {
            const beginTime = addForm.activityTime[0];
            const endTime = addForm.activityTime[1];
            let res;
            // console.log("提交数据：", addForm);
            if (isEdit.value) {
                // 编辑接口，假设有 edithuodong 方法
                res = await edithuodong({ ...addForm, beginTime, endTime });
            } else {
                // 新增接口
                res = await addhuodong({ ...addForm, beginTime, endTime });
            }
            if (res && res.code == 200) {
                ElMessage.success({
                    type: "success",
                    message: res.msg
                });
                addDialogVisible.value = false;
                getData();
            }
        }
    });
}

onMounted(() => {
    getData();
});

</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
}

.el-form-item {
    margin-right: 20px;
    margin-bottom: 15px; // Adjust margin for better spacing
}

.mb8 {
    margin-bottom: 8px;
}

.el-pagination {
    margin-top: 20px;
    justify-content: center;
}
</style>